package cn.su.upload_download.controller;

import cn.su.upload_download.utils.CompressFileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import java.io.*;

/**
 * @author SuZuQi
 * @title: UploadController
 * @projectName upload_download
 * @description: TODO
 * @date 2019/6/28
 */



@Controller
@RequestMapping("upload")
@Slf4j
public class UploadController {

    @PostMapping("file")
    public String  fileUpload(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename() ;
        if(fileName.endsWith(".zip")){
            File file1 = mf2File(file);
            CompressFileUtils.unZipFiles(file1,"D:/workspace_0425/front/public/static/js/");
            boolean flag = file1.delete();
            log.info("删除缓存文件：{}",flag?"成功":"失败") ;
        }else {
            InputStream in = file.getInputStream();
            File outFile = new File("E:/uploadDir/"+fileName);
            if(!outFile.exists()) outFile.createNewFile() ;
            FileOutputStream out = new FileOutputStream(outFile);
            byte[] by = new byte[1024];
            writeStream(in, out, by);
        }
        return "redirect:../index.html" ;
    }


    private  File mf2File(MultipartFile file) throws Exception {
        InputStream in = file.getInputStream();
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        File filePath = new File(path,"/static/temupload");
        if(!filePath.exists()) filePath.mkdirs();
        File outFile = new File(filePath,file.getOriginalFilename()) ;
        FileOutputStream out = new FileOutputStream(outFile) ;
        byte[] by = new byte[1024] ;
        writeStream(in, out, by);

        return outFile ;
    }




    private void writeStream(InputStream in, FileOutputStream out, byte[] by) throws IOException {
        int len;
        try{
            while((len=in.read(by))!=-1){
                out.write(by,0,len);
            }
        }finally{
            if (in != null) {
                try {
                    in.close();
                    System.out.println("in 已经关闭");
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                    System.out.println("out 已经关闭");
                } catch (IOException e) {
                }
            }
        }
    }


    public static void main(String[] args) {
    System.out.println(new File("D:\\workspace_learning\\upload_download/target/classes/static/temupload/WEBGL.zip").delete());
	}
}